package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.userextinfo.AlipayUserAuthDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.user.mini.MiniUserIdDto;
import com.uzai.console.dto.user.mini.MiniUserInfoUpdateDto;
import com.uzai.console.dto.user.mini.MiniUserQuery;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.UserExtInfoFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiCashierServerFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.MiniUserService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.service.user.MarketingRewardsService;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.user.MarketingRewardVo;
import com.uzai.console.vo.user.SysTagShow;
import com.uzai.console.vo.user.SysTagVo;
import com.uzai.console.vo.user.UserTreeVo;
import com.uzai.console.vo.user.mini.MiniUserInfoVo;
import com.uzai.console.vo.user.mini.MiniUserMinMaxCreateTimeVo;
import com.uzai.console.vo.user.mini.MiniUserPageVo;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class MiniUserServiceImpl extends CommonService implements MiniUserService {

    private Logger logger = LoggerFactory.getLogger(MiniUserServiceImpl.class);

    @Autowired
    private MiniUserMapper wechatUserMapper;
    @Autowired
    private MiniUserMapper miniUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private DeviceMiniInfoMapper deviceMiniInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private UzaiCashierServerFeignService uzaiCashierServerFeignService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private MarketingRewardsService marketingRewardsService;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private MarketingTagMapper marketingTagMapper;

    /**
     * 分页查询微信用户列表
     *
     * @param miniUserQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<MiniUserPageVo> findMiniUserList(MiniUserQuery miniUserQuery) {

        logger.info("---查询小程序会员列表---miniUserQuery={}", JSONObject.toJSONString(miniUserQuery));

        //返回到页面分页对象
        Page<MiniUserPageVo> pageVo = new Page<>();

        //新建返回到页面的LIST对象
        List<MiniUserPageVo> miniUserPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<MiniUser> page = new Page<>();
        miniUserQuery.convert(page);

        //判断是否有淘宝会员id条件
        if(StringUtils.isNotBlank(miniUserQuery.getSpecialId())){
            //清空其他条件
            MiniUserQuery miniUserQuery_specialId = new MiniUserQuery();
            miniUserQuery_specialId.setMerId(miniUserQuery.getMerId());
            miniUserQuery_specialId.setSize(miniUserQuery.getSize());
            miniUserQuery_specialId.setCurrent(miniUserQuery.getCurrent());
            miniUserQuery_specialId.setOrder(miniUserQuery.getOrder());
            miniUserQuery_specialId.setAsc(miniUserQuery.isAsc());
            miniUserQuery_specialId.setOrderByField(miniUserQuery.getOrderByField());
            miniUserQuery_specialId.setOrderItemList(miniUserQuery.getOrderItemList());
            miniUserQuery_specialId.setSpecialId(miniUserQuery.getSpecialId());
            //重新生成查询条件
            miniUserQuery = miniUserQuery_specialId;

            //查询淘宝会员信息
            TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
            tbUserInfoQuery.setMerId(miniUserQuery.getMerId());
            tbUserInfoQuery.setSpecialId(miniUserQuery.getSpecialId());
            List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(tbUserInfoQuery);
            if(tbUserInfoList != null && tbUserInfoList.size() > 0){
                List<Long> userIdList = new ArrayList<>();
                for (TbUserInfo tbUserInfo : tbUserInfoList) {
                    userIdList.add(tbUserInfo.getUserId());
                }
                miniUserQuery.setIdList(userIdList);
            }else{//未查询到淘宝会员id,则返回空
                return pageVo;
            }
        }

        List<MiniUser> miniUserList = miniUserMapper.findByList(page, miniUserQuery);
        if (miniUserList != null) {

            for (MiniUser miniUser : miniUserList) {
                MiniUserPageVo miniUserPageVo = new MiniUserPageVo();
                BeanUtils.copyProperties(miniUser, miniUserPageVo);

                try {
                    //身份名称
                    miniUserPageVo.setIdentityName(IdentityEnum.getById(miniUserPageVo.getIdentity()).getDesc());

                    //会员类型名称
                    if (miniUserPageVo.getUserType() != null) {
                        UserType userType = userTypeMapper.selectById(miniUserPageVo.getUserType(), miniUserQuery.getMerId());
                        if (userType != null) {
                            miniUserPageVo.setUserTypeName(userType.getName());
                        }
                    }

                    //上级用户
                    if (miniUserPageVo.getParentId() != null) {
                        if (miniUserPageVo.getParentId() != 0) {
                            MiniUser miniUserParent = miniUserMapper.selectById(miniUserPageVo.getParentId(), miniUserQuery.getMerId());
                            if (miniUserParent != null) {
                                miniUserPageVo.setParentName(miniUserParent.getNickName());
                            }
                        } else {
                            miniUserPageVo.setParentId(null);
                        }
                    }

                    //代理
                    if (miniUserPageVo.getAgentId() != null) {
                        if (miniUserPageVo.getAgentId() != 0) {
                            MiniUser miniUserAgent = miniUserMapper.selectById(miniUserPageVo.getAgentId(), miniUserQuery.getMerId());
                            if (miniUserAgent != null) {
                                miniUserPageVo.setAgentName(miniUserAgent.getNickName());
                            }
                        } else {
                            miniUserPageVo.setAgentId(null);
                        }
                    }

                    //合伙人
                    if (miniUserPageVo.getPartnerId() != null) {
                        if (miniUserPageVo.getPartnerId() != 0) {
                            MiniUser miniUserPartner = miniUserMapper.selectById(miniUserPageVo.getPartnerId(), miniUserQuery.getMerId());
                            if (miniUserPartner != null) {
                                miniUserPageVo.setPartnerName(miniUserPartner.getNickName());
                            }
                        } else {
                            miniUserPageVo.setPartnerId(null);
                        }
                    }

                    //查询机器人ID
                    if (miniUserPageVo.getDeviceUniqueId() != null) {
                        DeviceMiniInfo deviceMiniInfo = deviceMiniInfoMapper.selectById(miniUserPageVo.getDeviceUniqueId(), miniUserQuery.getMerId());
                        if (deviceMiniInfo != null) {
                            miniUserPageVo.setDeviceId(deviceMiniInfo.getDeviceId());
                            miniUserPageVo.setDeviceName(deviceMiniInfo.getDeviceName());
                            miniUserPageVo.setDeviceRemark(deviceMiniInfo.getDeviceRemark());
                            miniUserPageVo.setMiniOriginalId(deviceMiniInfo.getMiniOriginalId());
                        }
                    }

                    //用户类型组信息
                    if (miniUserPageVo.getUserType() != null) {
                        UserType userType = userTypeMapper.selectById(miniUserPageVo.getUserType(), miniUserQuery.getMerId());
                        if (userType != null) {
                            Long userTypeGroupId = userType.getGroupId();
                            if (userTypeGroupId != null) {
                                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, miniUserQuery.getMerId());
                                if (userTypeGroup != null) {
                                    miniUserPageVo.setUserTypeGroupId(userTypeGroup.getId());
                                    miniUserPageVo.setUserTypeGroupName(userTypeGroup.getName());
                                }
                            }
                        }
                    }

                    //标签List
                    try {
                        miniUserPageVo.setTagsArr(JSONObject.parseArray(miniUserPageVo.getTags(), String.class));
                    } catch (Exception e) { //如果不是JSON格式

                    }

                    //会员标签
                    if(StringUtils.isNotBlank(miniUser.getSysTags())){
                        try {
                            List<SysTagVo> userTagVoList =  JSONObject.parseArray(miniUser.getSysTags(), SysTagVo.class);
                            if(userTagVoList != null && userTagVoList.size() > 0){
                                List<SysTagShow> sysTagShowList = new ArrayList<>();
                                List<Long> sysTagsArr = new ArrayList<>();
                                for (SysTagVo userTagVo : userTagVoList) {
                                    sysTagsArr.add(userTagVo.getId());
                                    SysTagShow sysTagShow = new SysTagShow();
                                    BeanUtils.copyProperties(userTagVo, sysTagShow);
                                    //查询标签名称
                                    MarketingTag marketingTag = marketingTagMapper.selectById(userTagVo.getId(), miniUser.getMerId());
                                    if(marketingTag != null){
                                        sysTagShow.setName(marketingTag.getName());
                                    }
                                    sysTagShowList.add(sysTagShow);

                                }
                                miniUserPageVo.setSysTagsArr(sysTagsArr);
                                miniUserPageVo.setUserTagVoArr(sysTagShowList);
                            }
                        }catch (Exception e){ //如果不是JSON格式

                        }
                    }


                    //查询用户额外信息
                    UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                    userExtInfoQueryDto.setMerId(miniUserQuery.getMerId());
                    userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.MINI_PRO.getId()); //个人用户
                    userExtInfoQueryDto.setBizUserId(miniUserPageVo.getBizUserId());
                    List<String> keys = new ArrayList<>();
                    keys.add("ValidOrderCount"); //首字母大写
                    userExtInfoQueryDto.setKeys(keys);
                    UzaiRespVo<EsUserExtInfo> uzaiRespVo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                    //logger.info("----订单总量----uzaiRespVo="+JSONObject.toJSONString(uzaiRespVo));

                    if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                        EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                        if (esUserExtInfo != null) {
                            miniUserPageVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                        }
                    }
                    //是否在白名单当中
                    String id_white = miniUserQuery.getMerId() + "_" + miniUserPageVo.getBizUserId();
                    Map<String, Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                    if (white_map != null) {
                        miniUserPageVo.setBlacklistFlag(3); //白名单
                        miniUserPageVo.setBlacklistId(miniUserPageVo.getBizUserId());
                    }

                    //是否在全网黑名单当中
                    String id_blacklistPub = miniUserPageVo.getBizUserId();
                    Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                    if (pub_map != null) {
                        miniUserPageVo.setBlacklistFlag(2); //共享全网黑名单
                        miniUserPageVo.setBlacklistId(miniUserPageVo.getBizUserId());
                    }

                    String id_blacklistPrv = miniUserQuery.getMerId() + "_" + miniUserPageVo.getBizUserId();
                    Map<String, Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                    if (prv_map != null) { //在私有黑名单当中
                        miniUserPageVo.setBlacklistFlag(1); //私有黑名单
                        miniUserPageVo.setBlacklistId(id_blacklistPrv);
                    }
                } catch (Exception e) {

                }

                miniUserPageVoList.add(miniUserPageVo);
            }
        }

        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(miniUserPageVoList);
        //将返回对象排序(如果没有，则默认id排序降序)
        if (StringUtils.isBlank(miniUserQuery.getOrderByField()) && (miniUserQuery.getOrderItemList() == null || miniUserQuery.getOrderItemList().size() == 0)) {
            Tools.sort(miniUserPageVoList, "id", miniUserQuery.isAsc() ? "asc" : "desc");

        }
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询微信用户详情
     *
     * @param miniUserIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public MiniUserInfoVo findMiniUserInfo(@RequestBody MiniUserIdDto miniUserIdDto) {

        if (miniUserIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询页面用户
        MiniUser miniUser = miniUserMapper.selectById(miniUserIdDto.getId(), miniUserIdDto.getMerId());

        if (miniUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //返回给页面参数
        MiniUserInfoVo miniUserInfoVo = new MiniUserInfoVo();
        BeanUtils.copyProperties(miniUser, miniUserInfoVo);

        //判断是否需要脱敏,默认脱敏
        Boolean tuominFlag = true;
        String CMSTYPE_WECHATUSER_WXID_VERIFIED = (String) redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_WECHATUSER_WXID_VERIFIED, miniUserIdDto.getMerId(), miniUserInfoVo.getId()));
        if (StringUtils.isNotBlank(CMSTYPE_WECHATUSER_WXID_VERIFIED)) {
            tuominFlag = false;
        }

        //是否脱敏处理
        if (tuominFlag) {
            miniUserInfoVo.setWxid("");
        } else {
            miniUserInfoVo.setWxid(miniUser.getBizUserId());
        }

        //查询机器人ID
        if (miniUser.getDeviceUniqueId() != null) {
            DeviceMiniInfo deviceMiniInfo = deviceMiniInfoMapper.selectById(miniUser.getDeviceUniqueId(), miniUser.getMerId());
            if (deviceMiniInfo != null) {
                miniUserInfoVo.setDeviceId(deviceMiniInfo.getDeviceId());
                miniUserInfoVo.setDeviceName(deviceMiniInfo.getDeviceName());
                miniUserInfoVo.setDeviceRemark(deviceMiniInfo.getDeviceRemark());
                miniUserInfoVo.setMiniOriginalId(deviceMiniInfo.getMiniOriginalId());
            }
        }

        //用户类型组信息
        if (miniUser.getUserType() != null) {
            UserType userType = userTypeMapper.selectById(miniUser.getUserType(), miniUserIdDto.getMerId());
            if (userType != null) {
                Long userTypeGroupId = userType.getGroupId();
                if (userTypeGroupId != null) {
                    UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, miniUserIdDto.getMerId());
                    if (userTypeGroup != null) {
                        miniUserInfoVo.setUserTypeGroupId(userTypeGroup.getId());
                        miniUserInfoVo.setUserTypeGroupName(userTypeGroup.getName());
                    }
                }
            }
        }

        //标签
        try {
            miniUserInfoVo.setTagsArr(JSONObject.parseArray(miniUser.getTags(), String.class));
        } catch (Exception e) { //如果不是JSON格式
        }


        //会员标签
        if(StringUtils.isNotBlank(miniUser.getSysTags())){
            try {
                List<SysTagVo> userTagVoList =  JSONObject.parseArray(miniUser.getSysTags(), SysTagVo.class);
                if(userTagVoList != null && userTagVoList.size() > 0){
                    List<SysTagShow> sysTagShowList = new ArrayList<>();
                    List<Long> sysTagsArr = new ArrayList<>();
                    for (SysTagVo userTagVo : userTagVoList) {
                        sysTagsArr.add(userTagVo.getId());
                        SysTagShow sysTagShow = new SysTagShow();
                        BeanUtils.copyProperties(userTagVo, sysTagShow);
                        //查询标签名称
                        MarketingTag marketingTag = marketingTagMapper.selectById(userTagVo.getId(), miniUser.getMerId());
                        if(marketingTag != null){
                            sysTagShow.setName(marketingTag.getName());
                        }
                        sysTagShowList.add(sysTagShow);

                    }
                    miniUserInfoVo.setSysTagsArr(sysTagsArr);
                    miniUserInfoVo.setUserTagVoArr(sysTagShowList);
                }
            }catch (Exception e){ //如果不是JSON格式

            }
        }

        //上级、代理、合伙人如果为0，变成null
        if (miniUserInfoVo.getParentId() != null && miniUserInfoVo.getParentId().longValue() == 0) {
            miniUserInfoVo.setParentId(null);
        }
        if (miniUserInfoVo.getAgentId() != null && miniUserInfoVo.getAgentId().longValue() == 0) {
            miniUserInfoVo.setAgentId(null);
        }
        if (miniUserInfoVo.getPartnerId() != null && miniUserInfoVo.getPartnerId().longValue() == 0) {
            miniUserInfoVo.setPartnerId(null);
        }

        //上级买家树
        if (StringUtils.isNotBlank(miniUserInfoVo.getParentInfo())) {
            String parentInfo = miniUserInfoVo.getParentInfo();
            //买家树长度
            int parentInfoLength = parentInfo.length();
            if (parentInfoLength > 19) {//长度大于19，上级不止一层，判断是否有下划线拼接
                //统计下划线的总数
                int underlineCount = Tools.stringContainCharTimes(parentInfo, "_");
                //计算上级买家树长度层级数
                int parentCount = (parentInfoLength - underlineCount) / 19;
                //判断计算出的买家树层级数与下划线的个数是否匹配，就是层数为下线线数+1
                if (parentCount == underlineCount + 1) { //如果买家数匹配上下划线数量，则不处理
                    String[] parentIdList = miniUserInfoVo.getParentInfo().split("_");
                    if (parentIdList != null && parentIdList.length > 0) {
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList) {
                            UserTreeVo userTreeVo = new UserTreeVo();
                            MiniUser miniUser_parent = miniUserMapper.selectById(Long.valueOf(parentId), miniUserIdDto.getMerId());
                            if (miniUser_parent != null) {
                                userTreeVo.setId(miniUser_parent.getId());
                                userTreeVo.setNickName(miniUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        miniUserInfoVo.setParentInfoList(parentInfoList);
                    }
                } else {//未匹配上，则需要清除下划线，重新修改买家树信息
                    parentInfo = parentInfo.replaceAll("_", "");
                    String[] parentIdList = Tools.stringToStringArray(parentInfo, 19);
                    if (parentIdList != null && parentIdList.length > 0) {
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList) {
                            UserTreeVo userTreeVo = new UserTreeVo();
                            MiniUser miniUser_parent = miniUserMapper.selectById(Long.valueOf(parentId), miniUserIdDto.getMerId());
                            if (miniUser_parent != null) {
                                userTreeVo.setId(miniUser_parent.getId());
                                userTreeVo.setNickName(miniUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        miniUserInfoVo.setParentInfoList(parentInfoList);

                        //手动修改买家树
                        String parentInfoNew = StringUtils.join(parentIdList, "_");
                        miniUser.setParentInfo(parentInfoNew);
                        miniUserMapper.updateParetInfo(miniUser);
                    }
                }
            } else {//就一层上级，没有下划线，直接查询该上级信息
                UserTreeVo userTreeVo = new UserTreeVo();
                MiniUser miniUser_parent = miniUserMapper.selectById(Long.valueOf(parentInfo), miniUserIdDto.getMerId());
                if (miniUser_parent != null) {
                    List<UserTreeVo> parentInfoList = new ArrayList<>();
                    userTreeVo.setId(miniUser_parent.getId());
                    userTreeVo.setNickName(miniUser_parent.getNickName());
                    parentInfoList.add(userTreeVo);
                    miniUserInfoVo.setParentInfoList(parentInfoList);
                }
            }
        }

        //上级代理树
        if (StringUtils.isNotBlank(miniUserInfoVo.getAgentInfo())) {
            String[] agentIdList = miniUserInfoVo.getAgentInfo().split("_");
            if (agentIdList != null && agentIdList.length > 0) {
                List<UserTreeVo> agentInfoList = new ArrayList<>();
                for (String agentId : agentIdList) {
                    UserTreeVo userTreeVo = new UserTreeVo();
                    MiniUser miniUser_agent = miniUserMapper.selectById(Long.valueOf(agentId), miniUserIdDto.getMerId());
                    if (miniUser_agent != null) {
                        userTreeVo.setId(miniUser_agent.getId());
                        userTreeVo.setNickName(miniUser_agent.getNickName());
                        agentInfoList.add(userTreeVo);
                    }
                }
                miniUserInfoVo.setAgentInfoList(agentInfoList);
            }
        }

        //是否在全网黑名单当中
        String id_blacklistPub = miniUser.getBizUserId();
        Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
        if (pub_map != null) {
            miniUserInfoVo.setBlacklistFlag(2); //共享全网黑名单
            miniUserInfoVo.setBlacklistId(miniUser.getBizUserId());
        }

        //是否在白名单当中
        String id_white = miniUser.getMerId() + "_" + miniUser.getBizUserId();
        Map<String, Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
        if (white_map != null) {
            miniUserInfoVo.setBlacklistFlag(3); //白名单
            miniUserInfoVo.setBlacklistId(miniUser.getBizUserId());
        }

        String id_blacklistPrv = miniUser.getMerId() + "_" + miniUser.getBizUserId();
        Map<String, Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
        if (prv_map != null) { //在私有黑名单当中
            miniUserInfoVo.setBlacklistFlag(1); //私有黑名单
            miniUserInfoVo.setBlacklistId(id_blacklistPrv);
        }

        //会员互通信息
        if (StringUtils.isNotBlank(miniUser.getUzaiUnionId())) {
            try {
                //互通的公众号会员信息
                WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(miniUser.getUzaiUnionId(), miniUser.getMerId());
                if (wxpubUser != null) {
                    miniUserInfoVo.setWxpubUserId(wxpubUser.getId());
                }

                //互通的企业微信会员信息
                WxworkUser wxworkUser = wxworkUserMapper.selectByUzaiUnionId(miniUser.getUzaiUnionId(), miniUser.getMerId());
                if (wxworkUser != null) {
                    miniUserInfoVo.setWxworkUserId(wxworkUser.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--通过unionId查询互通企业或者互通公众号出现异常--, uzaiUnionId={}", miniUser.getUzaiUnionId());
            }

        }

        //如果会员昵称和会员头像都为空，则从ES中更新下信息
        if (StringUtils.isBlank(miniUser.getNickName()) || StringUtils.isBlank(miniUser.getHeadImg())) {
            //从ES中获取个人微信信息
            if (miniUser.getDeviceUniqueId() != null) {
                DeviceMiniInfo deviceMiniInfo = deviceMiniInfoMapper.selectById(miniUser.getDeviceUniqueId(), miniUserIdDto.getMerId());
                if (deviceMiniInfo != null) {
                    if (StringUtils.isNotBlank(deviceMiniInfo.getDeviceId())) {
                        String esId = miniUser.getMerId() + "_" + deviceMiniInfo.getDeviceId() + "_" + miniUser.getBizUserId();
                        try {

                            //通过查询运营商其他索引分片获取分片索引
                            String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, miniUserIdDto.getMerId());
                            Map<String, Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, esId, null);
                            WxContactsInfoVo wxContactsInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxContactsInfoVo.class);
                            if (wxContactsInfoVo != null) {
                                //更新微信信息
                                // miniUser.setWxid(wxContactsInfoVo.getWxid());
                                miniUser.setNickName(wxContactsInfoVo.getNick());
                                miniUser.setHeadImg(wxContactsInfoVo.getHimg());
                                miniUser.setRemark(wxContactsInfoVo.getRemark());
                                miniUserMapper.updateById(miniUser);

                                //返回给页面
                                // miniUser.setWxid(wxContactsInfoVo.getWxid());
                                miniUserInfoVo.setNickName(wxContactsInfoVo.getNick());
                                miniUserInfoVo.setHeadImg(wxContactsInfoVo.getHimg());
                                miniUserInfoVo.setRemark(wxContactsInfoVo.getRemark());
                            }
                        } catch (Exception e) {
                            logger.error("从ES中同步通讯录:error={}", e);
                        }
                    }
                }
            }
        }

        try {
            //关联其他机器人
            List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>();
            miniUserInfoVo.setDeviceInfoList(deviceInfoVoList);
            if (StringUtils.isNotBlank(miniUser.getDeviceInfos())) {
                List<Long> deviceInfoList = JSONObject.parseArray(miniUser.getDeviceInfos(), Long.class);
                if (deviceInfoList != null && deviceInfoList.size() > 0) {
                    for (Long deviceUniqueId : deviceInfoList) {
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, DeviceTypeEnum.MINI_PRO.getKey(), miniUser.getMerId());
                        if (device != null) {
                            DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                            BeanUtils.copyProperties(device, deviceInfoVo);
                            deviceInfoVoList.add(deviceInfoVo);
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        try {
            //营销数据
            // TODO: 2023/4/6 待修改es名称
            String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
            String marketingRewardId = miniUser.getId() + "" + miniUser.getRegSource();
            Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
            MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
            if (marketingRewardVo == null) {
                marketingRewardVo = new MarketingRewardVo(true);
            }
            miniUserInfoVo.setMarketingReward(marketingRewardVo);

        } catch (Exception e) {

        }

        //淘宝SID,默认查询第一条
        TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
        tbUserInfoQuery.setMerId(miniUser.getMerId());
        tbUserInfoQuery.setUserId(miniUser.getId());
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(new Page<>(), tbUserInfoQuery);
        if(tbUserInfoList != null && tbUserInfoList.size() > 0){
            miniUserInfoVo.setSpecialId(tbUserInfoList.get(0).getSpecialId());
        }

        return miniUserInfoVo;
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteUserById(Long id, Long merId) {
        MiniUser miniUser = miniUserMapper.selectById(id, merId);
        if (miniUser == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        int now = DateUtil.getNowTime();

        //真删除
        miniUserMapper.deleteById(id, merId);

        //删除缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.MINI_USER_ID.getKey(), merId, miniUser.getBizUserId()));

        //删除ES
        try {
            //删除会员基本信息
            String uzai_user_info_id = DeviceTypeEnum.MINI_PRO.getKey() + "_" + miniUser.getMerId() + "_" + miniUser.getBizUserId();
            String uzai_user_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_INFO, miniUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_info, uzai_user_info_id);

            //删除会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.MINI_PRO.getKey() + "_" + miniUser.getMerId() + "_" + miniUser.getBizUserId();
            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, miniUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_ext_info, uzai_user_ext_info_id);

            //删除营销奖励信息
            String uzai_user_marketing_reward_info_id = miniUser.getId() + "" + miniUser.getRegSource();
            elasticsearchUtil.deleteDataById(EsIndexName.UZAI_MARKETING_REWARD_INFO, uzai_user_marketing_reward_info_id);

        } catch (Exception e) {
            logger.error("删除ES会员扩展信息出现异常:{}" + e.getMessage());
        }


        //根据此会员的身份来查询下级用户
        if (miniUser.getIdentity().intValue() == IdentityEnum.BUYER.getId()) { //此会员是买家
            //查询所有下级买家
            MiniUserQuery miniUserQuery = new MiniUserQuery();
            miniUserQuery.setMerId(miniUser.getMerId());
            miniUserQuery.setParentId(miniUser.getId());
            //查询总数
            Integer count = miniUserMapper.findCount(miniUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<MiniUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<MiniUser> miniUserList = miniUserMapper.findByList(page, miniUserQuery);
                    if(miniUserList != null && miniUserList.size() > 0){
                        for(MiniUser miniUser_son : miniUserList) {
                            try {
                                //旧上级树
                                String parentInfoOld_Nson = miniUser_son.getParentInfo();
                                //将此会员的上级清空
                                miniUser_son.setParentId(0L);
                                miniUser_son.setParentInfo("");
                                miniUserMapper.updateIdentityInfo(miniUser_son);
                                //批量替换清空
                                miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", miniUser_son.getMerId(), true);
                                miniUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", miniUser_son.getMerId(), false);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", miniUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
//            //查询总数
//            Integer count = miniUserMapper.findCount(miniUserQuery);
//            //有总数，且最小创建时间有
//            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
//                        if (miniUserList != null && miniUserList.size() > 0) {
//                            for (MiniUser miniUser_son : miniUserList) {
//                                //旧上级树
//                                String parentInfoOld_Nson = miniUser_son.getParentInfo();
//                                //将此会员的上级清空
//                                miniUser_son.setParentId(0L);
//                                miniUser_son.setParentInfo("");
//                                miniUserMapper.updateIdentityInfo(miniUser_son);
//                                //批量替换清空
//                                miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", miniUser_son.getMerId(), true);
//                                miniUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", miniUser_son.getMerId(), false);
//                            }
//                        }
//                    }
//                }
//            }
        } else if (miniUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//代理身份
            //查询所有下级代理
            MiniUserQuery miniUserQuery = new MiniUserQuery();
            miniUserQuery.setMerId(miniUser.getMerId());
            miniUserQuery.setAgentId(miniUser.getId());

            //查询总数
            Integer count = miniUserMapper.findCount(miniUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<MiniUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<MiniUser> miniUserList = miniUserMapper.findByList(page, miniUserQuery);
                    if(miniUserList != null && miniUserList.size() > 0){
                        for(MiniUser miniUser_son : miniUserList) {
                            try {
                                //旧代理树
                                String agentInfoOld_Nson = miniUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                miniUser_son.setAgentId(0L);
                                miniUser_son.setAgentInfo("");
                                miniUserMapper.updateIdentityInfo(miniUser_son);
                                //批量替换
                                miniUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", miniUser_son.getMerId(), true);
                                miniUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", miniUser_son.getMerId(), false);

                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", miniUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
//            //查询总数
//            Integer count = miniUserMapper.findCount(miniUserQuery);
//            //有总数，且最小创建时间有
//            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
//                        if (miniUserList != null && miniUserList.size() > 0) {
//                            for (MiniUser miniUser_son : miniUserList) {
//                                //旧代理树
//                                String agentInfoOld_Nson = miniUser_son.getAgentInfo();
//                                //将此会员的代理信息给下级代理
//                                miniUser_son.setAgentId(0L);
//                                miniUser_son.setAgentInfo("");
//                                miniUserMapper.updateIdentityInfo(miniUser_son);
//                                //批量替换
//                                miniUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", miniUser_son.getMerId(), true);
//                                miniUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", miniUser_son.getMerId(), false);
//
//                            }
//                        }
//                    }
//                }
//            }
        } else if (miniUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//合伙人身份
            //查询所有下级代理
            MiniUserQuery miniUserQuery = new MiniUserQuery();
            miniUserQuery.setMerId(miniUser.getMerId());
            miniUserQuery.setPartnerId(miniUser.getId());

            //查询总数
            Integer count = miniUserMapper.findCount(miniUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<MiniUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<MiniUser> miniUserList = miniUserMapper.findByList(page, miniUserQuery);
                    if(miniUserList != null && miniUserList.size() > 0){
                        for(MiniUser miniUser_son : miniUserList) {
                            try {
                                //清空合伙人
                                miniUser_son.setPartnerId(0L);
                                miniUserMapper.updateIdentityInfo(miniUser_son);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", miniUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
//            //查询总数
//            Integer count = miniUserMapper.findCount(miniUserQuery);
//            //有总数，且最小创建时间有
//            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
//                        if (miniUserList != null && miniUserList.size() > 0) {
//                            for (MiniUser miniUser_son : miniUserList) {
//                                //清空合伙人
//                                miniUser_son.setPartnerId(0L);
//                                miniUserMapper.updateIdentityInfo(miniUser_son);
//                            }
//                        }
//                    }
//                }
//            }
        }
    }


    /**
     * 修改微信用户详情信息
     *
     * @param updateDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateMiniUserInfo(MiniUserInfoUpdateDto updateDto) {

        if (updateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        MiniUser miniUser = miniUserMapper.selectById(updateDto.getId(), updateDto.getMerId());

        if (miniUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取运营商ID
        Long merId = miniUser.getMerId();
        //用户Id
        Long id = miniUser.getId();

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员信息;");

        //微信昵称
        if (!Tools.getStr(updateDto.getNickName()).equals(Tools.getStr(miniUser.getNickName()))) {
            miniUser.setNickName(Tools.getStr(updateDto.getNickName()));
        }

        //会员类型
        if (updateDto.getUserType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不能为空");
        }
        UserType userType = userTypeMapper.selectById(updateDto.getUserType(), miniUser.getMerId());
        if (userType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不存在或已删除");
        }

        //是否修改会员类型
        if (Tools.getLong(updateDto.getUserType()).longValue() != Tools.getLong(miniUser.getUserType()).longValue()) {
            miniUser.setUserType(updateDto.getUserType());
            content.append("新会员类型:" + userType.getName()).append(";");
        }

        //支付宝姓名
        Boolean updateAlipayInfoFlag = false;
        if (!Tools.getStr(updateDto.getAlipayName()).equals(Tools.getStr(miniUser.getAlipayName()))) {
            miniUser.setAlipayName(updateDto.getAlipayName());
            updateAlipayInfoFlag = true;
        }

        //支付宝账号
        if (!Tools.getStr(updateDto.getAlipayAccount()).equals(Tools.getStr(miniUser.getAlipayAccount()))) {
            miniUser.setAlipayAccount(updateDto.getAlipayAccount());
            updateAlipayInfoFlag = true;
        }

        //淘宝订单尾号
//        if(Tools.getInteger(updateDto.getTbLastOrderNo()).intValue() != Tools.getInteger(miniUser.getTbLastOrderNo()).intValue()){
//            miniUser.setTbLastOrderNo(Tools.getInteger(updateDto.getTbLastOrderNo()));
//        }

        //最后下单时间
        if(Tools.getInteger(updateDto.getLastOrderTime()).intValue() != Tools.getInteger(miniUser.getLastOrderTime()).intValue()){
            miniUser.setLastOrderTime(Tools.getInteger(updateDto.getLastOrderTime()));
        }

        //自定义标签
        List<String> addTagsList = updateDto.getTagsArr();
        String tagsStr = Tools.getStrEmpty(JSONObject.toJSONString(addTagsList));
        if (!tagsStr.equals(Tools.getStrEmpty(miniUser.getTags()))) {
            miniUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(addTagsList)));
        }

        //会员标签
        List<SysTagVo> sysTagsList = updateDto.getSysTagsList();
        String sysTagsStr = Tools.getStrEmpty(JSONObject.toJSONString(sysTagsList));
        if(!sysTagsStr.equals(Tools.getStrEmpty(miniUser.getSysTags()))){
            miniUser.setSysTags(sysTagsStr);
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        if (!Tools.getStr(updateDto.getRemark()).equals(Tools.getStr(miniUser.getRemark()))) { //修改了备注
            //备注
            miniUser.setRemark(updateDto.getRemark());
            setRemarkFlag = true;
        }

        //身份
        if (updateDto.getIdentity() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "身份不能为空");
        }

        if (userType.getIdentity().intValue() != updateDto.getIdentity().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的会员类型与会员身份不一样");
        }

        //是否修改身份证标志
        boolean flag_identity = false;
        //旧身份
        int identityOld = miniUser.getIdentity().intValue();
        //新身份
        int identityNew = updateDto.getIdentity().intValue();

        //旧上级买家
        long parentIdOld = Tools.getLong(miniUser.getParentId()).longValue();

        //旧代理
        long agentIdOld = Tools.getLong(miniUser.getAgentId()).longValue();

        //旧合伙人
        long partnerIdOld = Tools.getLong(miniUser.getPartnerId()).longValue();

        //旧身份自己买家树
        String parentInfoOld_wo = Tools.getStr(miniUser.getParentInfo());

        //旧身份的所有下级的上级买家树
        String parentInfoOld_son = null;
        if (parentIdOld != 0) {
            parentInfoOld_son = Tools.getStrConnect(String.valueOf(miniUser.getId()), "_", parentInfoOld_wo);
        } else {
            parentInfoOld_son = String.valueOf(miniUser.getId());
        }

        //旧身份自己的代理树
        String agentInfoOld_wo = Tools.getStr(miniUser.getAgentInfo());

        //旧身份的下级的代理树
        String agentInfoOld_son = null;
        if (agentIdOld != 0) {
            agentInfoOld_son = Tools.getStrConnect(String.valueOf(miniUser.getId()), "_", agentInfoOld_wo);
        } else {
            agentInfoOld_son = String.valueOf(miniUser.getId());
        }

        //如果新身份是合伙人:合伙人、代理、上级买家全部清空
        if (identityNew == IdentityEnum.PARTNER.getId()) {
            updateDto.setPartnerId(0L); //修改合伙人
            updateDto.setAgentId(0L); //修改代理
            updateDto.setParentId(0L); //修改上级买家
        } else if (identityNew == IdentityEnum.AGENT.getId()) { //如果新身份是代理:上级买家清空
            updateDto.setParentId(0L);
        }

        //判断是否修改了身份
        if (identityNew != identityOld) { //修改身份
            flag_identity = true;       //修改身份标志为true
            miniUser.setIdentity(identityNew); //修改身份属性值
            content.append("新身份:" + IdentityEnum.getById(identityNew).getDesc()).append(";");
        }

        //新上级买家
        long parentIdNew = Tools.getLong(updateDto.getParentId()).longValue();

        //新代理
        long agentIdNew = Tools.getLong(updateDto.getAgentId()).longValue();

        //新合伙人
        long partnerIdNew = Tools.getLong(updateDto.getPartnerId()).longValue();

        //验证合伙人ID是否为合伙人
        boolean flag_partner = false;
        if (partnerIdNew != partnerIdOld) { //修改了合伙人

            //标志合伙人已经修改
            flag_partner = true;

            miniUser.setPartnerId(partnerIdNew); //修改自己的合伙人信息

            //选择了合伙人，验证对方身份
            if (partnerIdNew != 0) {
                MiniUser miniUserPartner_new = miniUserMapper.selectById(partnerIdNew, updateDto.getMerId());
                //判断存不存在
                if (miniUserPartner_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if (miniUserPartner_new.getIdentity() == null || miniUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if (miniUserPartner_new.getId().longValue() == miniUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
                content.append("新合伙人:" + partnerIdNew).append(";");
            } else {
                content.append("清空合伙人").append(";");
            }
        }

        //验证上级会员ID是否为买家
        boolean flag_parent = false;
        String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
        String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的
        if (parentIdNew != parentIdOld) {//修改了上级买家
            //标志上级买家已经修改
            flag_parent = true;
            //修改上级买家ID
            miniUser.setParentId(parentIdNew);

            //验收上级买家
            if (parentIdNew != 0) { //选择了上级买家
                MiniUser miniUserParent_new = miniUserMapper.selectById(parentIdNew, updateDto.getMerId());
                //判断存不存在
                if (miniUserParent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }
                //判断身份
                if (miniUserParent_new.getIdentity() == null || miniUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if (miniUserParent_new.getId().longValue() == miniUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(miniUserParent_new.getParentInfo());
                if (parentInfo.contains(String.valueOf(miniUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }
                //判断新上级买家是否有上级买家，
                if (Tools.getLong(miniUserParent_new.getParentId()).longValue() != 0) {//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(miniUserParent_new.getId()), "_", miniUserParent_new.getParentInfo());
                    miniUser.setParentInfo(parentInfoNew_wo);
                } else {
                    parentInfoNew_wo = String.valueOf(miniUserParent_new.getId());
                    miniUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(miniUser.getId()), "_", parentInfoNew_wo);

                content.append("新上级:" + parentIdNew).append(";");

            } else { //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                miniUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(miniUser.getId());

                content.append("清空上级").append(";");
            }
        }

        //验证代理身份是否为代理人
        boolean flag_agent = false;
        String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
        String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的
        if (agentIdNew != agentIdOld) { //表示修改了上级代理
            //标志上级代理已经修改
            flag_agent = true;
            //修改代理属性
            miniUser.setAgentId(agentIdNew);

            if (agentIdNew != 0) { //选择了上级代理，需要验证身份
                MiniUser miniUserAgent_new = miniUserMapper.selectById(agentIdNew, updateDto.getMerId());
                //判断存不存在
                if (miniUserAgent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if (miniUserAgent_new.getIdentity() == null || miniUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if (miniUserAgent_new.getId().longValue() == miniUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(miniUserAgent_new.getAgentInfo());
                if (agentInfo.contains(String.valueOf(miniUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if (Tools.getLong(miniUserAgent_new.getAgentId()) != 0) { //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(miniUserAgent_new.getId()), "_", miniUserAgent_new.getAgentInfo());
                    miniUser.setAgentInfo(agentInfoNew_wo);
                } else {
                    agentInfoNew_wo = String.valueOf(miniUserAgent_new.getId());
                    miniUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(miniUser.getId()), "_", agentInfoNew_wo);

                content.append("新代理:" + agentIdNew).append(";");

            } else { //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                miniUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(miniUser.getId());
                content.append("清空代理").append(";");
            }
        }

        //修改微信用户详情信息
        miniUserMapper.updateById(miniUser);

        //修改身份，改变了其他用户的树
        if (flag_identity) {
            //判断旧身份类型
            if (identityOld == IdentityEnum.BUYER.getId()) { // 旧身份是买家
                //判断新身份
                if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                    /**买家转代理-身份往上升
                     * 1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                    miniUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfoNew_son, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    miniUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    MiniUserQuery miniUserQuery = new MiniUserQuery();
                    miniUserQuery.setMerId(merId);
                    miniUserQuery.setParentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
                    //查询总数
                    Integer count = miniUserMapper.findCount(miniUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
                                if (miniUserList != null && miniUserList.size() > 0) {
                                    for (MiniUser miniUser_son : miniUserList) {
                                        miniUser_son.setParentId(0L);   //清空上级
                                        miniUser_son.setParentInfo(""); //清空上级树
                                        miniUser_son.setAgentId(id);    //修改代理
                                        miniUser_son.setAgentInfo(agentInfoNew_son); //修改代理树
                                        miniUserMapper.updateIdentityInfo(miniUser_son);
                                        //4:将下N级代理和下N级代理的树更新
                                        String agentInfoOld_Nson = String.valueOf(miniUser_son.getId());
                                        String agentInfoNew_Nson = miniUser_son.getId() + "_" + miniUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        miniUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        miniUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                    /**买家转合伙人-身份往上升
                     * 1: 批量将下N级无合伙人的用户合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无合伙人的合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                    miniUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    miniUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    MiniUserQuery miniUserQuery = new MiniUserQuery();
                    miniUserQuery.setMerId(merId);
                    miniUserQuery.setParentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
                    //查询总数
                    Integer count = miniUserMapper.findCount(miniUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
                                if (miniUserList != null && miniUserList.size() > 0) {
                                    for (MiniUser miniUser_son : miniUserList) {
                                        miniUser_son.setParentId(0L);   //清空上级
                                        miniUser_son.setParentInfo(""); //清空上级树
                                        miniUser_son.setPartnerId(id);    //修改合伙人
                                        miniUserMapper.updateIdentityInfo(miniUser_son);
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (identityOld == IdentityEnum.AGENT.getId()) { //旧身份是代理
                //判断新身份
                if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                    /**代理转买家-身份往下降
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                    //miniUserMapper.batchUpdateParentInfoFromAgentInfoAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);

                    //2:修改下N级代理树
                    //分俩次替换（避免替换留下"_"符合）
                    miniUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_wo, merId, true);
                    miniUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_wo, merId, false);

                    //3: 修改下级的代理和代理树
                    MiniUserQuery miniUserQuery = new MiniUserQuery();
                    miniUserQuery.setMerId(merId);
                    miniUserQuery.setAgentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
                    //查询总数
                    Integer count = miniUserMapper.findCount(miniUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
                                if (miniUserList != null && miniUserList.size() > 0) {
                                    for (MiniUser miniUser_son : miniUserList) {
                                        miniUser_son.setAgentId(agentIdNew);           // 修改新的上级代理
                                        miniUser_son.setAgentInfo(agentInfoNew_wo);    //修改新的代理树

                                        //买家为空，且身份是买家
                                        if (miniUser_son.getParentId().longValue() == 0L && miniUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                            miniUser_son.setParentId(id);                  //修改上级
                                            miniUser_son.setParentInfo(parentInfoNew_son); //修改上级树
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(miniUser_son.getId());
                                            String parentInfoNew_Nson = miniUser_son.getId() + "_" + miniUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            miniUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }

                                        miniUserMapper.updateIdentityInfo(miniUser_son);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                    /**代理转合伙人-身份往上升
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无合伙人的会员，将合伙人设置为此Id，满足条件:A:代理树包含此ID，B:合伙人为空；
                    miniUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);
                    //2:修改下N级代理树(清空截断）
                    //分俩次替换（避免替换留下"_"符合）
                    miniUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "", merId, true);
                    miniUserMapper.batchUpdateAgentInfo(agentInfoOld_son, "", merId, false);
                    //3: 修改下级的代理和代理树
                    MiniUserQuery miniUserQuery = new MiniUserQuery();
                    miniUserQuery.setMerId(merId);
                    miniUserQuery.setAgentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
                    //查询总数
                    Integer count = miniUserMapper.findCount(miniUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
                                if (miniUserList != null && miniUserList.size() > 0) {
                                    for (MiniUser miniUser_son : miniUserList) {
                                        miniUser_son.setAgentId(0L);                    // 清空代理人
                                        miniUser_son.setAgentInfo("");                  //清空代理人信息
                                        miniUser_son.setPartnerId(id);                  //修改合伙人
                                        miniUserMapper.updateIdentityInfo(miniUser_son);
                                    }
                                }
                            }
                        }
                    }
                }
            } else { //旧身份是合伙人
                //判断新身份
                if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                    /**合伙人转买家-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                     *  2:清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //miniUserMapper.batchUpdateParentInfoFromPartnerIdAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    MiniUserQuery miniUserQuery = new MiniUserQuery();
                    miniUserQuery.setMerId(merId);
                    miniUserQuery.setPartnerId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
                    //查询总数
                    Integer count = miniUserMapper.findCount(miniUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
                                if (miniUserList != null && miniUserList.size() > 0) {
                                    for (MiniUser miniUser_son : miniUserList) {
                                        miniUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是买家
                                        if (miniUser_son.getParentId().longValue() == 0L && miniUser_son.getAgentId().longValue() == 0L && miniUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                            miniUser_son.setParentId(id);                   //修改上级
                                            miniUser_son.setParentInfo(parentInfoNew_son);  //修改上级树
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(miniUser_son.getId());
                                            String parentInfoNew_Nson = miniUser_son.getId() + "_" + miniUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            miniUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }
                                        miniUserMapper.updateIdentityInfo(miniUser_son);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                    /**合伙人转代理-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                     *  2:清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //miniUserMapper.batchUpdateAgentInfoFromPartnerIdAndAgentIdNull(id, parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    MiniUserQuery miniUserQuery = new MiniUserQuery();
                    miniUserQuery.setMerId(merId);
                    miniUserQuery.setPartnerId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    MiniUserMinMaxCreateTimeVo minMaxCreateTimeVo = miniUserMapper.findMinAndMaxCreateTime(miniUserQuery);
                    //查询总数
                    Integer count = miniUserMapper.findCount(miniUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                miniUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                miniUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<MiniUser> miniUserList = miniUserMapper.findByList(miniUserQuery);
                                if (miniUserList != null && miniUserList.size() > 0) {
                                    for (MiniUser miniUser_son : miniUserList) {

                                        miniUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是代理
                                        if (miniUser_son.getParentId().longValue() == 0L && miniUser_son.getAgentId().longValue() == 0L && miniUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()) {
                                            miniUser_son.setAgentId(id);                   //修改代理
                                            miniUser_son.setAgentInfo(agentInfoNew_son);  //修改代理树

                                            //将下N级代理和下N级的代理树更新
                                            String agentInfoOld_Nson = String.valueOf(miniUser_son.getId());
                                            String agentInfoNew_Nson = miniUser_son.getId() + "_" + miniUser_son.getAgentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            miniUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                            miniUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                        }

                                        miniUserMapper.updateIdentityInfo(miniUser_son);

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //如果修改了上级买家,批量修改下N级买家树
        if (flag_parent) {
            //分俩次替换（避免替换留下"_"符合）
            miniUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            miniUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
        }

        //如果修改了代理,批量修改下N级代理树
        if (flag_agent) {
            //分俩次替换（避免替换留下"_"符合）
            miniUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            miniUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
        }

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if (setRemarkFlag) {
            //查询机器人
            //发送MQ消息
            MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
            SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
            msgDto.setContent(setUserRemarkDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceUniqueId(miniUser.getDeviceUniqueId());
            msgDto.setDeviceType(DeviceTypeEnum.MINI_PRO.getId());
            msgDto.setMerId(miniUser.getMerId());
            msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
            setUserRemarkDto.setWxid(miniUser.getBizUserId());
            setUserRemarkDto.setRemark(Tools.getStr(miniUser.getRemark()));
            noticeMsgPushProducerService.setUserRemark(msgDto);

        }

        //是否修改了支付宝账号和姓名
        if (updateAlipayInfoFlag) {
            AlipayUserAuthDto alipayUserAuthDto = new AlipayUserAuthDto();
            alipayUserAuthDto.setAlipayUserId(miniUser.getAlipayAccount());
            alipayUserAuthDto.setAlipayUserName(miniUser.getAlipayName());
            alipayUserAuthDto.setUserId(String.valueOf(miniUser.getId()));
            //获取该会员的appid配置1-获取默认机器人;2-获取机器人的配置方案；3-从配置方案的提现配置里获取appid
            if (miniUser.getDeviceUniqueId() != null) {
                DeviceMiniInfo deviceMiniInfo = deviceMiniInfoMapper.selectById(miniUser.getDeviceUniqueId(), miniUser.getMerId());
                if (deviceMiniInfo != null && deviceMiniInfo.getConfigId() != null) {
                    ConfigPlan configPlan = configPlanMapper.selectById(deviceMiniInfo.getConfigId(), deviceMiniInfo.getMerId());
                    if (configPlan != null && configPlan.getUserTakeBalId() != null) {
                        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
                        if (sysPlugin != null && StringUtils.isNotBlank(sysPlugin.getData())) {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                String zf_app_id = jsonObject.getString("zf_app_id");//账房appId
                                if (StringUtils.isNotBlank(zf_app_id)) {
                                    alipayUserAuthDto.setAppId(zf_app_id);
                                    UzaiRespVo<Object> objectUzaiRespVo = uzaiCashierServerFeignService.alipayUserAuth(alipayUserAuthDto);
                                    logger.info("--调用账房授权支付宝账号信息微服务接口--para={},result={}", JSONObject.toJSONString(alipayUserAuthDto), JSONObject.toJSONString(objectUzaiRespVo));
                                }
                            } catch (Exception e) {
                                logger.error("---配置方案的提现设置插件格式有问题---sysPluginId={}, configId={}, merId={}", sysPlugin.getId(), configPlan.getId(), configPlan.getMerId());
                            }
                        }
                    }
                }
            }
        }

        //发送异常报警通知-修改会员敏感信息
        if (StringUtils.isNotBlank(content)) {
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(updateDto.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, updateDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", miniUser.getNickName());
            ext.put("wxid", miniUser.getBizUserId());
            ext.put("userid", miniUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员敏感信息报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }

        //修改ES缓存
        //修改ES
        try {

            //修改营销策略数据
            if(flag_parent || flag_agent || flag_partner){
                marketingRewardsService.updateMarketingRewards(miniUser);
            }

            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.MINI_PRO.getKey() + "_" + miniUser.getMerId() + "_" + miniUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, miniUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(miniUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, miniUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        } catch (Exception e) {
            logger.error("修改会员营销策略信息出现异常:{}" + e.getMessage());
        }

    }

}
